# Copyright (C) 2004 The Written Word, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# $Id: lockfile.py 236 2006-09-19 22:19:40Z china $
#
# obtain read/write locks on files.

import os

from fcntl import lockf, LOCK_EX, LOCK_NB, LOCK_SH
from fnmatch import fnmatch
from struct import pack


# exceptions
class LockfileError (Exception):
  """base class for all exceptions raised by this module"""

  def __init__ (self, arg = None):
    self.msg = arg

  def __str__ (self):
    return self.msg

class LockfileFileLockedError (LockfileError):
  """file currently locked"""


def read_lock (fh):
  try:
    lockf (fh, LOCK_SH | LOCK_NB)
  except IOError, msg:
    if fnmatch (str (msg), '*Resource temporarily unavailable'):
      raise LockfileFileLockedError (str (msg))
    raise LockfileError (str (msg))

def write_lock (fh):
  try:
    lockf (fh, LOCK_EX | LOCK_NB)
  except IOError, msg:
    if fnmatch (str (msg), '*Resource temporarily unavailable'):
      raise LockfileFileLockedError (str (msg))
    raise LockfileError (str (msg))
